//
//  HYClientController.m
//  XPlayer
//
//  Created by 张水 on 2023/10/25.
//

#import "HYClientSocketController.h"
#import <HYFTFFIleTransfer/HYTCPClientManager.h>
#import "HYClientSocketCollectionViewCell.h"
#import "HYClientSocketViewModel.h"
#import "HYFileImportViewController.h"

@interface HYClientSocketController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>

@property (nonatomic, strong) UICollectionView *collectionView;

@property (nonatomic, strong) HYClientSocketViewModel *viewModel;

@end

@implementation HYClientSocketController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = AppBgThemeColor;
    [self congfigTCPClient];
    self.navigationBarView.titleLabel.text = self.name;
    self.navigationBarView.navagationBarStyle = Left_button_Show;
    [self.navigationBarView.leftButton setImage:[UIImage imageNamed:@"nav_btn_close_n"] forState:UIControlStateNormal];
    [self congfigUI];
    [self loadData];
    [self bindSignal];
}

- (void)congfigUI
{
    [self.view addSubview:self.collectionView];
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.navigationBarView.mas_bottom);
        make.left.right.equalTo(self.view);
        make.bottom.mas_equalTo(-HOME_BAR_HEIGHT);
    }];
}
- (void)leftButtonClick
{
    [self dismissViewControllerAnimated:YES completion:^{
            
    }];
}

- (void)dealloc
{
    [[HYTCPClientManager share] closeClient];
}

- (void)congfigTCPClient
{
    [[HYTCPClientManager share] initSocket];
    [HYTCPClientManager share].host = self.host;
    BOOL isConnect =  [HYTCPClientManager share].connect;
    if (isConnect) {
        [HYHub showMessage:NSLocalizedString(@"连接成功,请选择文件发送",nil)];
    }
}

- (void)loadData
{
    [self.viewModel loadData];
    [self.collectionView reloadData];
}
- (void)bindSignal
{
    @weakify(self);
    [self.viewModel.updatedContentSignal subscribeNext:^(id x) {
        @strongify(self);
        if ([x isEqualToString:@"0"]) {
            [self openAlbum];
        }
        if ([x isEqualToString:@"1"]) {
            HYFileImportViewController *documentFolderVC = [[HYFileImportViewController alloc]initWithParentPath:@"" currentfolderPath:[HYFileManager documentDirectory] currentfolderName:NSLocalizedString(@"文件导入", nil)];
            documentFolderVC.isSelectFile = YES;
            documentFolderVC.selectFile = ^(NSString *filePath, NSString *fileName, NSString *fileSuffixName) {
                NSData *data = [NSData dataWithContentsOfFile:filePath];
                NSString *type = [fileName componentsSeparatedByString:@"."].lastObject;
                [[HYTCPClientManager share] sendData:data fileName:fileName type:type];
            };
            documentFolderVC.modalPresentationStyle = UIModalPresentationFullScreen;
            [self presentViewController:documentFolderVC animated:YES completion:nil];
        }
    }];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return [self.viewModel numberOfSectionsInCollectionView:section];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    HYClientSocketCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CEllIDHYClientSocketCollectionViewCell" forIndexPath:indexPath];
    [cell bindViewModel:[self.viewModel cellForRowAtIndexPathInCollectionView:indexPath]];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    [self.viewModel didSelectItemAtIndexPath:indexPath];
}


- (void)openAlbum{
    UIImagePickerController *picker=[[UIImagePickerController alloc] init];
    picker.modalPresentationStyle = UIModalPresentationFullScreen;
    picker.delegate=self;
    picker.allowsEditing=NO;
    picker.videoMaximumDuration = 1.0;//视频最长长度
    picker.videoQuality = UIImagePickerControllerQualityTypeMedium;//视频质量
    picker.mediaTypes = [NSArray arrayWithObjects:@"public.movie", @"public.image",nil];
    picker.sourceType= UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    [self presentViewController:picker animated:YES completion:^{
    
    }];
}
#pragma mark UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    //图片
    if ([mediaType isEqualToString:@"public.image"]){
        NSURL *url = info[UIImagePickerControllerImageURL];
        NSData *data = [NSData dataWithContentsOfURL:url];
        NSString *lastName = [url lastPathComponent];
        NSString *fileTypeName = [NSString stringWithFormat:@".%@",[lastName componentsSeparatedByString:@"."].lastObject];
        NSMutableString *mutStr = [NSMutableString stringWithString:lastName];
        NSRange range = {0,lastName.length};
        [mutStr replaceOccurrencesOfString:fileTypeName withString:@"" options:NSLiteralSearch range:range];
        [[HYTCPClientManager share] sendData:data fileName:mutStr type:fileTypeName];
    }
    //视频
    if ([mediaType isEqualToString:@"public.movie"]){
        NSURL *url = info [UIImagePickerControllerMediaURL];//获得视频的URL
        NSData *data = [NSData dataWithContentsOfURL:url];
        NSArray *array = [[NSString stringWithFormat:@"%@",url] componentsSeparatedByString:@"/"];
        NSArray *fileLastPath = [(NSString *)array.lastObject componentsSeparatedByString:@"."];
        NSString *type = fileLastPath.lastObject;
        [[HYTCPClientManager share] sendData:data fileName:array.lastObject type:type];
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (UICollectionView *)collectionView
{
    if (_collectionView == nil) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
        layout.itemSize = CGSizeMake(kItemWidth(2), kItemHeight(2));
        layout.minimumLineSpacing = kItemSpace;
        layout.minimumInteritemSpacing = kItemSpace;
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:layout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.backgroundColor = AppBgThemeColor;
        _collectionView.contentInset = UIEdgeInsetsMake(kItemSpace, kItemSpace, kItemSpace, kItemSpace);
        [_collectionView registerClass:[HYClientSocketCollectionViewCell class] forCellWithReuseIdentifier:@"CEllIDHYClientSocketCollectionViewCell"];
        _collectionView.showsHorizontalScrollIndicator = NO;
    }
    return _collectionView;
}

- (HYClientSocketViewModel *)viewModel
{
    if (_viewModel == nil) {
        _viewModel = [[HYClientSocketViewModel alloc]init];
    }
    return _viewModel;
}
@end
